<template>
  <div class="protocol-info-display">
    <div v-if="protocol">
      <a-card title="协议基本信息" size="small" style="margin-bottom: 16px;">
        <a-descriptions bordered size="small" :column="2">
          <a-descriptions-item label="协议ID">
            <a-tag color="blue">{{ protocol.protocolId }}</a-tag>
          </a-descriptions-item>
          <a-descriptions-item label="协议名称">
            <span style="font-weight: 500;">{{ protocol.name }}</span>
          </a-descriptions-item>
          <a-descriptions-item label="协议版本">
            <a-tag color="green">{{ protocol.version }}</a-tag>
          </a-descriptions-item>
          <a-descriptions-item label="协议类型">
            <a-tag :color="getProtocolTypeColor(protocol.protocolType)">
              {{ getProtocolTypeName(protocol.protocolType) }}
            </a-tag>
          </a-descriptions-item>

          <!-- 渠道协议特有字段 -->
          <template v-if="isChannelProtocol">
            <a-descriptions-item label="渠道代码">
              <a-tag color="blue">{{ getChannelCode() }}</a-tag>
            </a-descriptions-item>
            <a-descriptions-item label="渠道名称">
              <span style="font-weight: 500;">{{ getChannelName() }}</span>
            </a-descriptions-item>
          </template>

          <!-- 活码协议特有字段 -->
          <template v-if="isQRCodeProtocol">
            <a-descriptions-item label="活码类型">
              <a-tag color="purple">{{ (protocol as QRCodeConfigProtocol).codeType }}</a-tag>
            </a-descriptions-item>
            <a-descriptions-item label="支持渠道">
              <a-space>
                <a-tag v-for="channel in (protocol as QRCodeConfigProtocol).channels || []" :key="channel" color="blue" size="small">
                  {{ getChannelDisplayName(channel) }}
                </a-tag>
              </a-space>
            </a-descriptions-item>
          </template>

          <a-descriptions-item label="是否默认">
            <a-tag :color="isDefault ? 'orange' : 'blue'">
              {{ isDefault ? '是' : '否' }}
            </a-tag>
          </a-descriptions-item>
          <a-descriptions-item label="字段数量">
            {{ allFields.length }}
          </a-descriptions-item>
          <a-descriptions-item label="描述" :span="2">
            <div style="color: #666; line-height: 1.5;">{{ protocol.description }}</div>
          </a-descriptions-item>
        </a-descriptions>
      </a-card>

      <!-- 配置字段 - 分区显示 -->
      <a-card title="配置字段" size="small" style="margin-bottom: 16px;">
        <a-tabs v-if="configSections.length > 0" type="card">
          <a-tab-pane
            v-for="section in configSections"
            :key="`field-${section.sectionKey}`"
            :tab="section.sectionName"
          >
            <a-table
              :columns="fieldColumns"
              :data-source="section.fields"
              :pagination="false"
              size="small"
            >
              <template #bodyCell="{ column, record }">
                <template v-if="column.key === 'required'">
                  <a-tag :color="record.required ? 'red' : 'green'">
                    {{ record.required ? '必填' : '可选' }}
                  </a-tag>
                </template>
                <template v-else-if="column.key === 'fieldType'">
                  <a-tag color="blue">{{ record.fieldType }}</a-tag>
                </template>
                <template v-else-if="column.key === 'defaultValue'">
                  <code style="background: #f6f8fa; padding: 2px 4px; border-radius: 3px;">
                    {{ formatDefaultValue(record.defaultValue) }}
                  </code>
                </template>
                <template v-else-if="column.key === 'fieldName'">
                  <span style="font-weight: 500;">{{ record.fieldName }}</span>
                </template>
              </template>
            </a-table>
          </a-tab-pane>
        </a-tabs>
                 <a-table
           v-else
           :columns="fieldColumns"
           :data-source="allFields"
           :pagination="false"
           size="small"
         >
          <template #bodyCell="{ column, record }">
            <template v-if="column.key === 'required'">
              <a-tag :color="record.required ? 'red' : 'green'">
                {{ record.required ? '必填' : '可选' }}
              </a-tag>
            </template>
            <template v-else-if="column.key === 'fieldType'">
              <a-tag color="blue">{{ record.fieldType }}</a-tag>
            </template>
            <template v-else-if="column.key === 'defaultValue'">
              <code style="background: #f6f8fa; padding: 2px 4px; border-radius: 3px;">
                {{ formatDefaultValue(record.defaultValue) }}
              </code>
            </template>
            <template v-else-if="column.key === 'fieldName'">
              <span style="font-weight: 500;">{{ record.fieldName }}</span>
            </template>
          </template>
        </a-table>
      </a-card>

      <!-- 默认配置值 - 分区显示 -->
      <a-card title="默认配置值" size="small" style="margin-bottom: 16px;">
        <a-tabs v-if="defaultValueSections.length > 0" type="card">
          <a-tab-pane
            v-for="section in defaultValueSections"
            :key="`default-${section.sectionKey}`"
            :tab="section.sectionName"
          >
            <div class="protocol-json-display">
              <pre>{{ JSON.stringify(section.defaultValues, null, 2) }}</pre>
            </div>
          </a-tab-pane>
        </a-tabs>
                 <div v-else class="protocol-json-display">
           <pre>{{ JSON.stringify(getAllDefaultValues(), null, 2) }}</pre>
         </div>
      </a-card>

      <!-- 元数据信息 -->
      <a-card v-if="protocol.metadata" title="元数据信息" size="small" style="margin-bottom: 16px;">
        <a-descriptions bordered size="small" :column="2">
          <a-descriptions-item v-if="protocol.metadata.author" label="作者">
            {{ protocol.metadata.author }}
          </a-descriptions-item>
          <a-descriptions-item v-if="protocol.metadata.category" label="分类">
            <a-tag color="orange">{{ protocol.metadata.category }}</a-tag>
          </a-descriptions-item>
          <a-descriptions-item v-if="protocol.metadata.createTime" label="创建时间">
            {{ protocol.metadata.createTime }}
          </a-descriptions-item>
          <a-descriptions-item v-if="protocol.metadata.updateTime" label="更新时间">
            {{ protocol.metadata.updateTime }}
          </a-descriptions-item>
          <a-descriptions-item v-if="protocol.metadata.tags" label="标签" :span="2">
            <a-space>
              <a-tag v-for="tag in protocol.metadata.tags" :key="tag" color="cyan" size="small">
                {{ tag }}
              </a-tag>
            </a-space>
          </a-descriptions-item>
          <a-descriptions-item v-if="protocol.metadata.documentation" label="文档说明" :span="2">
            <div style="color: #666; line-height: 1.5;">{{ protocol.metadata.documentation }}</div>
          </a-descriptions-item>
        </a-descriptions>
      </a-card>

      <!-- JSON 操作区域 -->
      <a-card title="JSON 操作" size="small">
        <div class="json-operations">
          <a-space>
            <a-button @click="exportProtocol" type="primary">
              <template #icon><ExportOutlined /></template>
              导出协议
            </a-button>
            <a-button @click="copyJson">
              <template #icon><CopyOutlined /></template>
              复制 JSON
            </a-button>
            <a-button @click="formatJson">
              <template #icon><FormatPainterOutlined /></template>
              格式化 JSON
            </a-button>
          </a-space>

          <div v-if="showFormattedJson" class="formatted-json">
            <pre><code>{{ formattedJsonString }}</code></pre>
          </div>
        </div>
      </a-card>
    </div>
    <div v-else class="no-protocol">
      <a-empty description="暂无协议信息" />
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, computed } from 'vue'
import { message } from 'ant-design-vue'
import {
  ExportOutlined,
  CopyOutlined,
  FormatPainterOutlined
} from '@ant-design/icons-vue'
import { ProtocolType3 } from '../types/protocol3-types'
import type { AnyProtocol, ChannelConfigProtocol, QRCodeConfigProtocol } from '../types/channel-config-protocol'

// Props
interface Props {
  protocol: AnyProtocol | null
  isDefault?: boolean
}

const props = withDefaults(defineProps<Props>(), {
  isDefault: false
})

// 响应式数据
const showFormattedJson = ref(false)
const formattedJsonString = ref('')

// 判断协议类型
const isChannelProtocol = computed(() =>
  props.protocol?.protocolType === ProtocolType3.MERCHANT_CHANNEL_CONFIG_V3
)

const isQRCodeProtocol = computed(() =>
  props.protocol?.protocolType === ProtocolType3.QR_CODE_CONFIG
)

// 获取配置分区数据
const configSections = computed(() => {
  if (!props.protocol?.configSections) return []
  return props.protocol.configSections
})

// 获取所有字段（用于无分区显示）
const allFields = computed(() => {
  if (!configSections.value.length) return []

  const fields: any[] = []
  configSections.value.forEach(section => {
    section.fields.forEach(field => {
      fields.push(field)
    })
  })

  return fields
})

// 创建默认值分区数据
const defaultValueSections = computed(() => {
  if (!configSections.value.length) return []

  return configSections.value.map(section => ({
    sectionKey: section.sectionKey,
    sectionName: section.sectionName,
    defaultValues: section.defaultValues || {}
  })).filter(section => Object.keys(section.defaultValues).length > 0)
})

// 获取所有默认值
const getAllDefaultValues = (): Record<string, any> => {
  const result: Record<string, any> = {}

  configSections.value.forEach(section => {
    if (section.defaultValues) {
      Object.assign(result, section.defaultValues)
    }
  })

  return result
}

// 字段表格列定义
const fieldColumns = [
  {
    title: '字段键',
    dataIndex: 'fieldKey',
    key: 'fieldKey',
    width: 120
  },
  {
    title: '字段名称',
    dataIndex: 'fieldName',
    key: 'fieldName',
    width: 120
  },
  {
    title: '类型',
    dataIndex: 'fieldType',
    key: 'fieldType',
    width: 80
  },
  {
    title: '必填',
    dataIndex: 'required',
    key: 'required',
    width: 60
  },
  {
    title: '默认值',
    dataIndex: 'defaultValue',
    key: 'defaultValue',
    width: 100
  },
  {
    title: '描述',
    dataIndex: 'description',
    key: 'description'
  }
]

// 协议类型颜色映射
const getProtocolTypeColor = (type: ProtocolType) => {
  const colorMap = {
    [ProtocolType3.MERCHANT_CHANNEL_CONFIG_V3]: 'blue',
    [ProtocolType3.QR_CODE_CONFIG]: 'green',
    [ProtocolType3.DEFAULT_PROTOCOL]: 'orange',
    'CHANNEL_ONBOARDING': 'purple'
  }
  return colorMap[type] || 'default'
}

// 协议类型名称映射
const getProtocolTypeName = (type: ProtocolType) => {
  const nameMap = {
    [ProtocolType3.MERCHANT_CHANNEL_CONFIG_V3]: '商户渠道配置',
    [ProtocolType3.QR_CODE_CONFIG]: '二维码配置',
    [ProtocolType3.DEFAULT_PROTOCOL]: '默认协议',
    'CHANNEL_ONBOARDING': '渠道进件协议'
  }
  return nameMap[type] || type
}

// 渠道显示名称映射
const getChannelDisplayName = (channelCode: string) => {
  const channelMap = {
    'CHANNEL_IF_WECHAT': '微信支付',
    'CHANNEL_IF_ALIPAY': '支付宝',
    'CHANNEL_IF_HUIFU': '汇付天下',
    'CHANNEL_IF_FUIOU': '富友支付',
    'CHANNEL_IF_DOUGONG': '斗拱支付',
    'CHANNEL_IF_LAKALA': '拉卡拉',
    'CHANNEL_IF_LESHUA': '乐刷支付'
  }
  return channelMap[channelCode as keyof typeof channelMap] || channelCode
}

// 获取渠道代码
const getChannelCode = () => {
  if (!props.protocol) return '-'

  // 尝试从Protocol3数据结构中获取
  if ('channelCode' in props.protocol && props.protocol.channelCode) {
    return props.protocol.channelCode
  }

  return '无渠道'
}

// 获取渠道名称
const getChannelName = () => {
  if (!props.protocol) return '-'

  // 尝试从Protocol3数据结构中获取
  if ('channelName' in props.protocol && props.protocol.channelName) {
    return props.protocol.channelName
  }

  // 根据渠道代码获取显示名称
  const channelCode = getChannelCode()
  if (channelCode && channelCode !== '无渠道' && channelCode !== '-') {
    return getChannelDisplayName(channelCode)
  }
  
  return '无渠道'
}

// 格式化默认值显示
const formatDefaultValue = (value: any) => {
  if (value === null || value === undefined) {
    return '-'
  }
  if (typeof value === 'object') {
    return JSON.stringify(value)
  }
  if (typeof value === 'string' && value === '') {
    return '空字符串'
  }
  return String(value)
}

// JSON操作方法
const exportProtocol = () => {
  if (!props.protocol) return

  const jsonString = JSON.stringify(props.protocol, null, 2)
  const blob = new Blob([jsonString], { type: 'application/json' })
  const url = URL.createObjectURL(blob)
  const a = document.createElement('a')
  a.href = url
  a.download = `${props.protocol.protocolId}.json`
  document.body.appendChild(a)
  a.click()
  document.body.removeChild(a)
  URL.revokeObjectURL(url)
  message.success('协议文件已下载')
}

const copyJson = async () => {
  try {
    const jsonString = JSON.stringify(props.protocol, null, 2)
    await navigator.clipboard.writeText(jsonString)
    message.success('JSON已复制到剪贴板')
  } catch (error) {
    message.error('复制失败')
  }
}

const formatJson = () => {
  try {
    formattedJsonString.value = JSON.stringify(props.protocol, null, 2)
    showFormattedJson.value = !showFormattedJson.value
  } catch (error) {
    console.error('JSON格式化失败:', error)
  }
}
</script>

<style scoped>
.protocol-info-display {
  width: 100%;
}

.no-protocol {
  text-align: center;
  padding: 40px 0;
}

:deep(.ant-descriptions-item-label) {
  font-weight: 500;
}

.protocol-json-display {
  max-height: 300px;
  overflow-y: auto;
}

.protocol-json-display pre {
  margin: 0;
  background-color: #f8f9fa;
  border: 1px solid #e9ecef;
  color: #495057;
  padding: 12px;
  border-radius: 6px;
  font-size: 12px;
  overflow-x: auto;
}

.json-operations {
  margin-bottom: 16px;

  .formatted-json {
    background: #f5f5f5;
    border: 1px solid #d9d9d9;
    border-radius: 4px;
    padding: 12px;
    max-height: 400px;
    overflow-y: auto;
    margin-top: 16px;

    pre {
      margin: 0;
      font-family: 'Consolas', 'Monaco', monospace;
      font-size: 12px;
      line-height: 1.5;
    }
  }
}
</style>